<?php
/**
 * @package pmapi
 * @copyright Copyright (c)2014 Enrico Fagnoni
 * @license GNU General Public License version 3, or later
 *
 * @since 1.0.0
 */
 
defined('_JEXEC') or die;

if (!class_exists('VirtueMartModelProduct')) require ( JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'product.php');

class PmapiModelProduct extends VirtueMartModelProduct 
{           
    public function getVendorCurrencyCode($vendorId)
    {
        if (!class_exists('VirtueMartModelVendor')) require ( JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'vendor.php');
        $currency = VirtueMartModelVendor::getVendorCurrency($vendorId);
        
        return  $currency->currency_code_3;
    } 
 
 
    public function getVendorUserId($vendorId)
    {
        if (!class_exists('VirtueMartModelvendor')) require ( JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'vendor.php');
        
        return VirtueMartModelvendor::getUserIdByVendorId($vendorId); 
    }
        
        
    public function getCurrentUserShopperGroups()
    {
        $xrefTable = $this->getTable('vmuser_shoppergroups');
        $sg  = $xrefTable->load(JFactory::getUser()->id);
        
        // ensure that user belongs to at least to a shopper group
        if (empty($sg) || !is_array($sg)) {
            $sg = array(ApiHelper::ANONYMOUS_SHOPPERGROUP_ID);
        }        
        
        return $sg;
    }
    
    
    public function getCustomFieldsParents(array $customFields)
    {
        //get unique parent list
        $parents=array();
        foreach ($customFields as $customField){
            if ($customField->custom_parent_id) $parents[$customField->custom_parent_id]=$customField->custom_parent_id;
        }
        
        //find parents description
        $select = 'published=1 AND ( FALSE';
        foreach ($parents as $parent) {
            $select .= ' OR virtuemart_custom_id= '. $parent;
        }
        $select .= ')';
        
        $db = $this->getDbo();
        $query = $db
            ->getQuery(true)
            ->select('*')
            ->from( '#__virtuemart_customs' )
            ->where( $select);
        $db->setQuery($query);
        
        return $db->loadObjectList();;
    }
    
    
    public function getItem()
    {                         
        $id = JFactory::getApplication()->input->get('id',null);
        $p = $this->getProduct(
            $id,                                //* @param int     $virtuemart_product_id
            true,                               //* @param boolean $front for frontend use
            VmConfig::get('show_prices', 1),    //* @param boolean $withCalc calculate prices?
            true,                               //* @param boolean published
            1,                                  //* @param int     quantity
            true                                //* @param boolean load customfields
        );

        // Check for errors.
        if (count($errors = $this->get('Errors')) || !$p->virtuemart_product_id) {
            throw new Exception(implode("\n", $errors)||'Not Found', 404);
        }
             
        //set a  sound default for gr:validFrom predicate         
        if ($p->product_price_publish_down==ApiHelper::EMPTY_DB_DATE) 
                $p->product_price_publish_down = $p->modified_on;
            
        //set a  sound default for gr:validThrough predicate 
        $offering_ttl = JComponentHelper::getParams('com_pmapi')->get('offering_ttl','+1 day');
        if ($p->product_price_publish_up==ApiHelper::EMPTY_DB_DATE)
                $p->product_price_publish_up = ApiHelper::datetime($offering_ttl);   
        
        // ensure that is an array
        if (!is_array($p->customfields)) $p->customfields = array();
        if (!is_array($p->categories)) $p->categories = array();
          
        // Inject additional data to product
        $p->shopper_groups = $this->getCurrentUserShopperGroups();
        $p->currency =  $this->getVendorCurrencyCode($p->virtuemart_vendor_id);
        $p->vendorUserId = $this->getVendorUserId($p->virtuemart_vendor_id);       
        $p->customFieldsParents =  $this->getCustomFieldsParents($p->customfields);
        
        //inject images in product
        $this->addImages($p);
        
        // ensure images is an array
        if (!is_array($p->images)) $p->images = array();
        
          
        return $p;
    }

}
// No closing tag